var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
///<reference path='../../index.d.ts'/>
import pdfjs from "pdfjs-dist";
import { orderBy } from "lodash";
// import worker from "pdfjs-dist/lib/pdf.worker.js"
// pdfjs.GlobalWorkerOptions.workerSrc = ''
// import 'pdfjs-dist/build/pdf.worker'
/**
 * 解析pdf类
 * @class CddPdf
 */
export default class CddPdf {
    /**
     * 构造函数
     * @constructor 构造函数
     * @param {Object} params 参数
     * @param params.options 配置
     */
    constructor(params) {
        /**解析后的图片地址 */
        this.imgs = [];
        /**Blob url与否，如果不是则是objectUrl */
        this.isBlobUrl = false;
        /**配置选项 */
        this.options = {
            /**伸缩质量 */
            scale: 2
        };
        if (!params) {
            throw new Error(`缺少参数 file 或者 url`);
        }
        else {
            this.file = params.file;
            this.url = params.url;
            this.isBlobUrl = params.isBlobUrl || this.isBlobUrl;
        }
        // 如果存在设置
        if (params.options) {
            this.options = Object.assign({}, this.options, params.options);
        }
        this.promise = this.init();
    }
    /**获取pdf */
    static GetPdf(params) {
        return new CddPdf(params).promise;
    }
    /**初始化数据 */
    init() {
        return __awaiter(this, void 0, void 0, function* () {
            // 获取数据
            const data = yield this.getData();
            //转化成图片
            this.imgs = orderBy(yield this.parsePdf(data), ['pageNumber']);
            console.log(`over`, this.imgs);
            return this;
            // 渲染pdf
        });
    }
    /**获取数据 */
    getData() {
        return new Promise((reso, reg) => {
            if (this.file) {
                const reader = new FileReader();
                reader.onload = (e) => reso(e.target.result);
                reader.readAsDataURL(this.file);
            }
            else if (this.url) {
                reso(this.fetchFile(this.url));
            }
        });
    }
    /**fetc获取文件内容 */
    fetchFile(url) {
        return new Promise((reso, rej) => {
            if (url && url.startsWith('http')) {
                /**获取数据 */
                fetch(url).then((res) => __awaiter(this, void 0, void 0, function* () {
                    const blob = yield res.blob();
                    reso(URL.createObjectURL(blob));
                }));
            }
            else {
                reso(url);
            }
        });
    }
    /**解析pdf文件 */
    parsePdf(file) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                return new Promise((reso, rej) => {
                    const loadingTask = pdfjs.getDocument(file);
                    const arr = [];
                    let count = 0;
                    if (loadingTask.promise) {
                        loadingTask.promise.then(pdf => {
                            if (pdf && pdf.numPages) {
                                for (let i = 1; i <= pdf.numPages; i++) {
                                    pdf.getPage(i).then((page) => __awaiter(this, void 0, void 0, function* () {
                                        arr.push(yield this.renderPage(page));
                                        count++;
                                        if (count === pdf.numPages) {
                                            reso(arr);
                                        }
                                    }));
                                }
                            }
                        });
                    }
                });
            }
            catch (error) {
                console.error(`渲染出错`, error);
            }
        });
    }
    /**渲染页面 */
    renderPage(page) {
        return new Promise((reso, rej) => {
            const viewport = page.getViewport({ scale: this.options.scale });
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            const renderContext = {
                canvasContext: ctx,
                viewport: viewport
            };
            //进行渲染
            page.render(renderContext).promise.then((res) => {
                if (this.isBlobUrl) {
                    canvas.toBlob((blob) => {
                        reso({
                            pageNumber: page.pageNumber,
                            // value: canvas.toDataURL('image/png', 1)
                            value: URL.createObjectURL(blob)
                        });
                    }, 'image/png', 1);
                }
                else {
                    reso({
                        pageNumber: page.pageNumber,
                        value: canvas.toDataURL('image/png', 1)
                    });
                }
            });
        });
    }
}
